package com.cu.jiekong.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cu.jiekong.constants.ResultStatus;
import com.cu.jiekong.frame.HystrixHandler;
import com.cu.jiekong.frame.model.Ret;
import com.cu.jiekong.model.User;
import com.cu.jiekong.util.StringUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * @author jintian
 * @date 14:43
 */
@Service
public class AppUserService {

    private Logger logger = LoggerFactory.getLogger(AppUserService.class);

    @Autowired
    private RestTemplate restTemplate;

    /**
     * rabbion 方式获取用户信息
     *
     * @param userId
     * @return
     */
    @HystrixCommand(fallbackMethod = "rabbonCallBack")
    public Ret getAppUserById(String userId) {
        MultiValueMap<String, String> requestJson = new LinkedMultiValueMap();
        requestJson.add("userId", userId + "");
        requestJson.add("sign", StringUtil.MD5(userId));
        String borrowUserStr = restTemplate.postForObject("http://user-system/user/getUserById", requestJson, String.class);

        Ret ret = JSON.parseObject(borrowUserStr, Ret.class);
        ret.setData(JSON.parseObject(((JSONObject) ret.getData()).toJSONString(), User.class));
        return ret;
    }

    public Ret rabbonCallBack(String userId) {
        logger.info("error userId : " + userId);
        return new Ret(ResultStatus.RESULT_400002.getCode(), ResultStatus.RESULT_400002.getMsg());
    }
}
